package conf

import (
	"encoding/json"
	"errors"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"os"
	"xorm.io/xorm"
)

var Env *config

func init() {
	Env = LoadEnv()
}

type config struct {
	Host     string
	Port     int
	Database []Database
	Redis    struct {
		Host     string
		Port     int
		Password string
		Db       int
	}
	Url struct {
		PermissionCenterURL string
		ShopUrl             string
		AppKey              string
		AppSecret           string
		AuthUrl             string
	}
}

type Database struct {
	Group    string
	Host     string
	Port     int
	User     string
	Password string
	Db       string
	Charset  string
}

func LoadEnv() *config {
	// 打开文件
	file, _ := os.Open("env.json")
	// 关闭文件
	defer file.Close()
	decoder := json.NewDecoder(file)

	conf := new(config)
	//Decode从输入流读取下一个json编码值并保存在v指向的值里
	err := decoder.Decode(&conf)
	if err != nil {
		panic(err)
	}
	return conf
}

func GetDb(group ...string) *xorm.Engine {
	if len(group) > 1 {
		panic(errors.New("database group is wrong"))
	}

	var dbconf Database
	if len(group) == 0 {
		dbconf = Env.Database[0]
	} else {
		exist := false
		for _, item := range Env.Database {
			if item.Group == group[0] {
				dbconf = item
				exist = true
				break
			}
		}
		if !exist {
			panic(errors.New("database group is wrong"))
		}
	}

	engine, err := xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s", dbconf.User, dbconf.Password, dbconf.Host, dbconf.Port, dbconf.Db, dbconf.Charset))
	if err != nil {
		panic(err)
	}

	engine.SetMaxIdleConns(40)
	return engine
}
